package com.cpecc.quartz;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import com.cpecc.dao.wuzi.BianMaDao;
import com.cpecc.model.wuzi.BianMa;

@Service
public class BianMaSchedule implements ServletContextAware{
	
	@Autowired
	private ServletContext servletContext;
	
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext  = context;
	}
	
	@Autowired
	private BianMaDao bianMaDao;

	public void bianMa() {
		String path = this.servletContext.getRealPath("/download/");
		try {
			Document doc = new SAXReader().read(new File(path,"demo_yyyyMMdd.xml"));
			List deleteList = doc.selectNodes("/WuLiaoBM/deleted");			
			for(Iterator iter=deleteList.iterator();iter.hasNext();) {
				Element el = (Element)iter.next();
				String wuLiaoBM=el.elementText("WuLiaoBM");
				BianMa bianMa=bianMaDao.getBianMa(wuLiaoBM);				
				if(bianMa!=null){
					bianMaDao.delete(bianMa);
				}
			}
			
			List itemList = doc.selectNodes("/WuLiaoBM/row");
			for(Iterator iter=itemList.iterator();iter.hasNext();) {
				Element el = (Element)iter.next();
				String wuLiaoBM=el.elementText("WuLiaoBM");
				if(wuLiaoBM==null)
					wuLiaoBM="";
				String wuLiaoMC=el.elementText("WuLiaoMC");
				if(wuLiaoMC==null)
					wuLiaoMC="";
				String guiGeXH="";
				String guiGe=el.elementText("GuiGe");
				if(guiGe!=null&&!guiGe.equals(""))
					guiGeXH+=guiGe;
				String xingHao=el.elementText("XingHao");
				if(xingHao!=null&&!xingHao.equals(""))
					guiGeXH=guiGeXH+"/"+xingHao;
				String caiZhi=el.elementText("CaiZhi");
				if(caiZhi!=null&&!caiZhi.equals(""))
					guiGeXH=guiGeXH+"/"+caiZhi;				
				BianMa bianMa=new BianMa();
				bianMa.setWuLiaoBM(wuLiaoBM);
				bianMa.setWuLiaoMC(wuLiaoMC);
				bianMa.setGuiGeXH(guiGeXH);
				bianMaDao.save(bianMa);				
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}